<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>账号管理</el-breadcrumb-item>
            <el-breadcrumb-item>账号管理</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">角色列表</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div class="inside-main-box">
          <el-row class="inside-main" style="height: 46px;">
            <el-col :span="6" style="margin-left: 20px;">
              <el-form-item label="用户名" size="small">
                <el-input v-model="formData.name" placeholder="请输入用户名"/>
              </el-form-item>
            </el-col>
            <el-col :span="6" style="margin-left: 20px;">
              <el-button size="small" icon="search" class="sele-but">查询</el-button>
              <el-button size="small" icon="plus" class="add-but" @click="modifyDetail()">新增</el-button>
            </el-col>
          </el-row>
        </div>
        <div style="height: 20px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px">
        </div>
        <div style="background: #fff;">
          <el-table :data="tableData.rows" style="width: 100%;">
            <el-table-column label="角色名称" prop="role_name" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" prop="create_date" align="center" show-overflow-tooltip :formatter="function(row,column){
              if(row.create_date){
                return $moment(row.create_date).format('YYYY-MM-DD HH:mm:ss')
              }else{
                return ''
              }
            }"></el-table-column>
            <el-table-column label="更新时间" prop="update_date" align="center"  show-overflow-tooltip :formatter="function(row,column){
              if(row.update_date){
                return $moment(row.update_date).format('YYYY-MM-DD HH:mm:ss')
              }else{
                return ''
              }
            }"></el-table-column>
            <el-table-column label="描述" prop="description" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="Operation" align="center" width="400">
              <template #default="item">
                <div v-if="item.row.id!=1">
                  <el-button plain size="small" type="text" icon="edit" @click="modifyDetail(item)" :disabled="item.row.id==1">修改</el-button>
                  <el-button size="small" type="danger" link plain icon="Delete" @click="handleDelete(item)" :disabled="item.row.id==1">删除</el-button>
                  <el-button size="small" type="text" plain icon="Setting" @click="handleConfig(item)" :disabled="item.row.id==1">配置</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="paginationBox">
            <el-pagination background
                           v-model:currentPage="obj.currentPage"
                           v-model:page-size="obj.pageSize"
                           layout="total,prev, pager, next,"
                           :total="tableData.total || 0"
                           @size-change="handleChangePage"
                           @current-change="handleChangePage"
            />
          </div>
        </div>
      </el-main>
    </el-container>
    <!-- 新增弹窗 -->
    <el-dialog v-model="centerDialogVisible" title="角色管理" width="40%">
      <div style="width:90%">
        <el-form ref="ruleFormRef" :model="formData.form" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <div>
              <el-input v-model="formData.form.role_name" placeholder="请输入" autocomplete="off" />
            </div>
            <div style="margin-left: 10px;">
              <span style="font-size: 2px;color: #888;">支持中文、英文、数字</span>
            </div>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="formData.form.description" type="textarea" placeholder="请选择">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
                <span class="dialog-footer">
                    <el-button class="sele-but" @click="saveRole(formData.form)">保存</el-button>
                    <el-button class="empty-but" @click="revert()">取消</el-button>
                </span>
      </template>
    </el-dialog>
    <el-dialog v-model="configShow" title="title" width="50%">
      <div style="width:98%">
        <el-tree :data="permissions"
        show-checkbox
        node-key="id"
        :props="{
          children:'subs',
          label:'title'
        }"
       :default-expanded-keys="defaultArray.array"
        ref="tree"
        check-on-click-node
        :expand-on-click-node="false"
        @check-change="handleCheckChange"
        @node-click="nodeclick"
        style="max-height: 500px; overflow-y: auto; width: 100%">
        </el-tree>
      </div>
      <template #footer>
                <span class="dialog-footer">
                    <el-button class="sele-but" @click="savePermission(formData.form)">保存</el-button>
                    <el-button class="empty-but" @click="configShow=false">取消</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import {queryAll,addRole,updateRole,deleteRole,getPermissions,savePermissions} from "@/api/role"
import {ElMessage, ElMessageBox} from "element-plus";
import permissions from "@/utils/permissions"
let obj = reactive({
  currentPage: 1,
  pageSize: 10,
});
let defaultArray = reactive({array:[]})
let formData = reactive({
  name:"",
  form:{
    role_name:"",
    description:"",
    permissions:[]
  }
});

let centerDialogVisible = ref(false);
let configShow = ref(false);

const handleSearch = (name) => {
  getTableData(name);
};

const handleChangePage = (e) => {
  obj = { ...obj, ...e };
  getTableData(null);
};

const handleConfig = (item) => {
  getPermissions(item.row).then(res=>{
    defaultArray.array = res.data;
    configShow.value = true;
  })
};

const modifyDetail = (item) => {
  if(item){
    formData.form = JSON.parse(JSON.stringify(item.row));
  }else{
    formData.form={
        role_name:"",
        description:"",
        permissions:[]
      };
  }
  centerDialogVisible.value = true;
};

const handleDelete = (item) =>{
  ElMessageBox.confirm("确定要删除吗?").then(()=>{
    let data = JSON.parse(JSON.stringify(item.row))
    deleteRole(data)
        .then((res) => {
          if(res.code=="200"){
            ElMessage({
              message: "success",
              type: "success",
            });
            getTableData(null);
          }else{
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
  });
}

const cancelOderDetail = () => {
  centerDialogVisible.value = false;
  configShow.value = false;
};

const saveRole = (item)=>{
  item.permissions = null;
  if(item.id){
    updateRole(item)
        .then((res) => {
          if(res.code=="200"){
            ElMessage({
              message: "success",
              type: "success",
            });
            revert()
          }else{
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }

        });
  }else{
    addRole(item)
        .then((res) => {
          if(res.code=="200"){
            ElMessage({
              message: "success",
              type: "success",
            });
            revert()
          }else{
            ElMessage({
              message: res.msg,
              type: "error",
            });
          }
        });
  }
};

const tree = ref();
const savePermission = ()=>{
  let arr = tree.value.getCheckedKeys();
  console.log(arr)
  formData.form
  updateRole(form)
      .then((res) => {
        if(res.code=="200"){
          ElMessage({
            message: "success",
            type: "success",
          });
        }else{
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
        // configShow.value = false;
      });
}
const revert = () =>{
  formData.form={
    role_name:"",
    description:"",
    permissions:[]
  };
  getTableData();
  centerDialogVisible.value=false;
}
let tableData = reactive({
  rows: [
  ],
  total:0
});

const getTableData = (name) => {
  if(name){
    obj.currentPage = 1;
  }
  console.log("permissions is",permissions)
  queryAll({
        name:name,
        pageNo: obj.currentPage || 1,
        pageSize: obj.pageSize || 10,
      })
      .then((res) => {
        let rows=[];
        res.data.forEach((e)=>{
          e.createTime = e.createTime?.substring(0,10);
          rows.push(e);
        })
        tableData.rows = rows;
        tableData.total = res.data.total
      });
};
let permissionList = reactive({
  standard: [
  ],
  rows: [
  ],
});
onMounted(() => {
  getTableData(null);
});
</script>

<style scoped>
/* 面包屑字体颜色更改 */
.breadcrumbColor>>>.el-breadcrumb__inner {
  color: #000;
}
/* 内部header */
.inside-header {
  height: 40px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
.paginationBox{
  display: flex;
  justify-content: flex-end;
}
/* 空心按钮样式 */
.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0;
  border-radius: 2px;
  color: white;
}

.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/* 分页 */
.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
